package com.deer.wms.system.manage.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deer.wms.intercept.annotation.Authority;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.constant.Constants;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.system.manage.model.poi.ExcelUtils;
import com.deer.wms.system.manage.model.user.*;
import com.deer.wms.system.manage.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户信息api接口
 * <p>
 *
 * @author guo
 * @since 2017/10/01
 */
@Api("用户信息api接口")
@RestController
@RequestMapping("/users")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private WareUserService wareUserService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    /**
     * 分页查账户信息
     *
     * @param criteria    UserInfoCriteria
     * @param currentUser 当前登录用户
     */
    @ApiOperation(value = "分页查账户信息", notes = "分页获取账户信息列表")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @GetMapping("/userList")
    public Result list(UserInfoCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (currentUser.getIsAdmin() == 1) {
            criteria.setIsAdmin(1);
        } else {
            criteria.setIsAdmin(0);
        }
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<UserInfoDto> list = userInfoService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 用户修改自己的密码
     *
     * @param userPassword userPassword封装类
     * @param currentUser  当前用户
     */
    @ApiOperation(value = "修改密码", notes = "用户修改自己的密码")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping("/password")
    public Result modifyPassword(@RequestBody UserPassword userPassword, @ApiIgnore @User CurrentUser currentUser) {
        if (!userPassword.getPassword().equals(userPassword.getConfirmPassword())) {
            return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "确认密码与新密码不一致", "确认密码与新密码不一致");
        }
        userInfoService.modifyPassword(userPassword, currentUser);
        return ResultGenerator.genSuccessResult("修改成功");
    }

    /**
     * 找回密码，设置密码
     *
     * @param retrieval
     */
    @ApiOperation(value = "找回密码，重置密码", notes = "找回密码，重新设置登录密码")
    @PutMapping("/retrieval/password")
    public Result retrievalPassword(@Valid @RequestBody UserPasswordRetrieval retrieval) {
        userInfoService.retrievalPassword(retrieval);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 获取当前登录用户的信息
     *
     * @param currentUser 当前登录用户信息
     * @return
     */
    @ApiOperation(value = "获取当前登录用户的信息", notes = "获取当前登录用户的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/info")
    public Result getCurrentUserDetail(@ApiIgnore @User CurrentUser currentUser) {
        UserDetail detail = userInfoService.findUserDetailByAccount(currentUser.getAccount());
        detail.setToken(currentUser.getToken());
        return ResultGenerator.genSuccessResult(detail);
    }

    /**
     * 用户修改自己的资料信息
     *
     * @param userData    userData封装类
     * @param currentUser 当前用户
     * @return
     */
    @ApiOperation(value = "修改个人信息", notes = "用户修改自己的个人信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @Authority
    @PostMapping("/info")
    public Result modifyInfo(UserData userData, HttpServletRequest request, @ApiIgnore @User CurrentUser currentUser) {
        userInfoService.modifyUserData(userData, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 新增账户信息
     *
     * @param create      账户信息
     * @param currentUser 当前操作人员信息
     * @return
     */
    @ApiOperation(value = "新增账户信息", notes = "新增账户信息")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping
    public Result createUserInfo(@Valid @RequestBody UserInfoCreate create, @ApiIgnore @User CurrentUser currentUser) {
        List<UserInfo> list = userInfoService.findByAccount(create.getAccount());
        if (list.size() != 0) {
            return ResultGenerator.genFailResult(CommonCode.ACCOUNT_EXISTS, null);
        }
        userInfoService.createUserInfo(create, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "验证用户账户是否已存在", notes = "")
    @GetMapping("/validUserAccount")
    public Result validUserAccount(String account) {
        List<UserInfo> list = userInfoService.findByAccount(account);
        if (list.size() != 0) {
            return ResultGenerator.genFailResult(CommonCode.ACCOUNT_EXISTS, null);
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 修改账户信息
     *
     * @param modify      账户信息
     * @param currentUser 当前操作人员信息
     * @return
     */
    @ApiOperation(value = "修改账户信息", notes = "修改账户信息")
    @Authority
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping("/modifyUserInfo")
    public Result modifyUserInfo(@RequestBody UserInfoModify modify, @ApiIgnore @User CurrentUser currentUser) {

        String account = modify.getAccount();
        List<UserInfo> userInfoList = userInfoService.findByAccount(account);

        if (userInfoList.size() == 1 && userInfoList.get(0).getUserId().equals(modify.getUserId())) {
            userInfoService.modifyUserInfo(modify, currentUser);
            return ResultGenerator.genSuccessResult();
        } else if (userInfoList.size() == 0) {
            userInfoService.modifyUserInfo(modify, currentUser);
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult(CommonCode.ACCOUNT_EXISTS, null);
        }

    }

    /**
     * 获取账户详细信息
     *
     * @param userId 账户信息id
     * @return
     */
    @ApiOperation(value = "获取账户详细信息", notes = "获取指定账户的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
            , @ApiImplicitParam(name = "userId", value = "账户信息id", paramType = "path", dataType = "int", required = true)
    })
    @Authority
    @GetMapping("/{userId}/info")
    public Result getUserInfoDetail(@PathVariable Integer userId) {
        UserInfoDetailVO vo = userInfoService.findUserInfoDetailByUserId(userId);
        return ResultGenerator.genSuccessResult(vo);
    }

    /**
     * 启用账户
     *
     * @param userId 用户信息id
     * @return
     */
    @ApiOperation(value = "启用账户", notes = "启用账户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/enable")
    public Result enable(Integer userId, @ApiIgnore @User CurrentUser currentUser) {
        userInfoService.modifyUserInfoAccountState(userId, Constants.ACCOUNT_STATUS_ENABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 停用账户
     *
     * @param userId 用户信息id
     * @return
     */
    @ApiOperation(value = "停用账户", notes = "停用账户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/disable")
    public Result disable(Integer userId, @ApiIgnore @User CurrentUser currentUser) {
        userInfoService.modifyUserInfoAccountState(userId, Constants.ACCOUNT_STATUS_DISABLE, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 删除账户
     *
     * @param userId 用户信息id
     * @return
     */
    @ApiOperation(value = "删除账户", notes = "删除账户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Authority
    @GetMapping("/delete")
    public Result delete(Integer userId, @ApiIgnore @User CurrentUser currentUser) {
        userInfoService.removeById(userId);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "一键启用禁用账户", notes = "一键启用禁用账户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @GetMapping("/updateUserInfoAccountStatus")
    public Result updateUserInfoAccountStatus(Integer accountStatus, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (accountStatus.equals(1)) {
            userInfoService.updateUserInfoAccountStatus("disable");
        } else if (accountStatus.equals(2)) {
            userInfoService.updateUserInfoAccountStatus("enable");
        }
        return ResultGenerator.genSuccessResult();
    }

    @Autowired
    private AreaUserService areaUserService;
    /**
     * 绑定仓库、角色、货主
     */
    @ApiOperation(value = "绑定仓库、角色、货主", notes = "绑定仓库、角色、货主")
    @ApiImplicitParams({@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)})
    @PostMapping("/bindWare")
    public Result bindWare(@RequestBody UserInfoCreate create, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        wareUserService.deleteByUserId(create.getUserId());
        areaUserService.deleteAreaByUserId(create.getUserId());
        userRoleService.deleteByUserId(create.getUserId());
        userOrganizationService.deleteByUserId(create.getUserId());
        if (create.getWareIds() != null && create.getWareIds().size() > 0) {
            Integer createUserId = currentUser.getUserId();
            userInfoService.bindWare(create, createUserId);
        }
        if (create.getAreaIds() != null && create.getAreaIds().size() > 0) {
            Integer createUserId = currentUser.getUserId();
            userInfoService.bindArea(create, createUserId);
        }
        if (create.getRoleIds() != null && create.getRoleIds().size() > 0) {
            userInfoService.bindRole(create);
        }
        if (create.getOrganizationIds() != null && create.getOrganizationIds().size() > 0) {
            userInfoService.bindOrganization(create);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/paresUserExcel")
    public Result paresItemExcel(String path) {
        String str = userInfoService.paresUserExcel(path);
        return ResultGenerator.genSuccessResult(str);
    }

    /**
     * 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result importUser(@RequestPart("file") MultipartFile file) throws Exception {
        List<UserVo> users = ExcelUtils.readMultipartFile(file, UserVo.class);
        users.stream().forEach(t->{
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getAccount,t.getUserCode());
            UserInfo one = userInfoService.getOne(queryWrapper);
            if (one == null){
                userInfoService.insertUser(t);
            }
        });
        return ResultGenerator.genSuccessResult();
    }

}
